<template>
  <div class="medical-record-management">
    <div class="page-header">
      <h1 class="page-title">病历管理</h1>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showCreateDialog = true">
          新建病历
        </el-button>
        <el-button :icon="Document" @click="showTemplateDialog = true">
          模板管理
        </el-button>
        <el-button :icon="Download" @click="exportRecords">
          导出病历
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #409EFF;">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ recordStats.total }}</div>
              <div class="stat-label">病历总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #67C23A;">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ recordStats.todayRecords }}</div>
              <div class="stat-label">今日病历</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card warning" @click="showPendingDialog = true">
          <div class="stat-content">
            <div class="stat-icon" style="background: #E6A23C;">
              <el-icon><EditPen /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ recordStats.pendingSignatures }}</div>
              <div class="stat-label">待签名</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background: #F56C6C;">
              <el-icon><Files /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ templates.length }}</div>
              <div class="stat-label">病历模板</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索患者姓名、医生或主诉"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="病历状态" clearable @change="handleFilter">
            <el-option label="草稿" value="草稿" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已审核" value="已审核" />
            <el-option label="已归档" value="已归档" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterDepartment" placeholder="科室" clearable @change="handleFilter">
            <el-option label="内分泌科" value="内分泌科" />
            <el-option label="心内科" value="心内科" />
            <el-option label="外科" value="外科" />
            <el-option label="儿科" value="儿科" />
            <el-option label="妇产科" value="妇产科" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterVisitType" placeholder="就诊类型" clearable @change="handleFilter">
            <el-option label="门诊" value="门诊" />
            <el-option label="急诊" value="急诊" />
            <el-option label="住院" value="住院" />
            <el-option label="体检" value="体检" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateRangeChange"
            style="width: 100%"
          />
        </el-col>
      </el-row>
    </el-card>

    <!-- 病历列表 -->
    <el-card shadow="never">
      <el-table
        :data="paginatedRecords"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="病历编号" width="100" />
        <el-table-column prop="patientName" label="患者姓名" width="100">
          <template #default="{ row }">
            <el-button type="text" @click="handleViewDetail(row)">
              {{ row.patientName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="doctorName" label="医生" width="100" />
        <el-table-column prop="department" label="科室" width="100" />
        <el-table-column prop="visitDate" label="就诊日期" width="110" />
        <el-table-column prop="visitType" label="就诊类型" width="80">
          <template #default="{ row }">
            <el-tag :type="getVisitTypeColor(row.visitType)" size="small">
              {{ row.visitType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="chiefComplaint" label="主诉" min-width="150" show-overflow-tooltip />
        <el-table-column prop="diagnosis" label="主要诊断" min-width="150">
          <template #default="{ row }">
            <el-tag 
              v-for="diagnosis in row.diagnosis.primary.slice(0, 2)" 
              :key="diagnosis"
              size="small"
              type="danger"
              class="diagnosis-tag"
            >
              {{ diagnosis }}
            </el-tag>
            <span v-if="row.diagnosis.primary.length > 2" class="more-diagnoses">
              +{{ row.diagnosis.primary.length - 2 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="签名状态" width="100">
          <template #default="{ row }">
            <div class="signature-status">
              <el-tooltip v-if="row.signatures.length > 0" content="查看签名详情">
                <el-tag 
                  :type="getSignatureColor(row.signatures)"
                  size="small"
                >
                  {{ getSignatureText(row.signatures) }}
                </el-tag>
              </el-tooltip>
              <span v-else class="no-signature">未签名</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              {{ row.status === '草稿' ? '继续编写' : '查看' }}
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="handleSign(row)"
              v-if="canSign(row)"
            >
              签名
            </el-button>
            <el-dropdown @command="(command: string) => handleMoreActions(command, row)">
              <el-button type="text" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="copy">复制病历</el-dropdown-item>
                  <el-dropdown-item command="template">保存为模板</el-dropdown-item>
                  <el-dropdown-item command="print">打印病历</el-dropdown-item>
                  <el-dropdown-item command="export">导出PDF</el-dropdown-item>
                  <el-dropdown-item command="archive" :disabled="row.status !== '已审核'">
                    归档
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" :disabled="row.status !== '草稿'">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredRecords.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建病历对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新建病历"
      width="900px"
      @close="resetCreateForm"
    >
      <div class="create-form">
        <el-form
          ref="createFormRef"
          :model="createForm"
          :rules="createRules"
          label-width="100px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="患者" prop="patientId">
                <el-select
                  v-model="createForm.patientId"
                  placeholder="请选择患者"
                  filterable
                  style="width: 100%"
                  @change="handlePatientSelect"
                >
                  <el-option
                    v-for="patient in patients"
                    :key="patient.id"
                    :label="`${patient.name} (${patient.phone})`"
                    :value="patient.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="就诊类型" prop="visitType">
                <el-select v-model="createForm.visitType" placeholder="请选择就诊类型">
                  <el-option label="门诊" value="门诊" />
                  <el-option label="急诊" value="急诊" />
                  <el-option label="住院" value="住院" />
                  <el-option label="体检" value="体检" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="就诊日期" prop="visitDate">
                <el-date-picker
                  v-model="createForm.visitDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用模板">
                <el-select
                  v-model="selectedTemplate"
                  placeholder="选择病历模板（可选）"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="template in templates"
                    :key="template.id"
                    :label="template.name"
                    :value="template.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreateRecord" :loading="loading">
            创建病历
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 病历详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="病历详情"
      width="1200px"
      append-to-body
    >
      <div v-if="currentRecord" class="record-detail">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="病历编号">{{ currentRecord.id }}</el-descriptions-item>
              <el-descriptions-item label="患者姓名">{{ currentRecord.patientName }}</el-descriptions-item>
              <el-descriptions-item label="医生">{{ currentRecord.doctorName }}</el-descriptions-item>
              <el-descriptions-item label="科室">{{ currentRecord.department }}</el-descriptions-item>
              <el-descriptions-item label="就诊日期">{{ currentRecord.visitDate }}</el-descriptions-item>
              <el-descriptions-item label="就诊类型">
                <el-tag :type="getVisitTypeColor(currentRecord.visitType)">
                  {{ currentRecord.visitType }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="病历状态">
                <el-tag :type="getStatusColor(currentRecord.status)">
                  {{ currentRecord.status }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime(currentRecord.createdAt) }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="病史记录" name="history">
            <div class="history-content">
              <div class="history-item">
                <h4>主诉</h4>
                <p>{{ currentRecord.chiefComplaint }}</p>
              </div>
              <div class="history-item">
                <h4>现病史</h4>
                <p>{{ currentRecord.presentIllness }}</p>
              </div>
              <div class="history-item">
                <h4>既往史</h4>
                <p>{{ currentRecord.pastHistory }}</p>
              </div>
              <div class="history-item">
                <h4>家族史</h4>
                <p>{{ currentRecord.familyHistory }}</p>
              </div>
              <div class="history-item">
                <h4>个人史</h4>
                <p>{{ currentRecord.personalHistory }}</p>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="检查诊断" name="examination">
            <div class="examination-content">
              <div class="exam-item">
                <h4>体格检查</h4>
                <p>{{ currentRecord.physicalExamination }}</p>
              </div>
              <div class="exam-item">
                <h4>辅助检查</h4>
                <ul>
                  <li v-for="exam in currentRecord.auxiliaryExamination" :key="exam">
                    {{ exam }}
                  </li>
                </ul>
              </div>
              <div class="exam-item">
                <h4>诊断</h4>
                <div class="diagnosis-section">
                  <div class="diagnosis-group">
                    <strong>主要诊断：</strong>
                    <el-tag 
                      v-for="diagnosis in currentRecord.diagnosis.primary" 
                      :key="diagnosis"
                      type="danger"
                      class="diagnosis-tag"
                    >
                      {{ diagnosis }}
                    </el-tag>
                  </div>
                  <div class="diagnosis-group" v-if="currentRecord.diagnosis.secondary.length > 0">
                    <strong>次要诊断：</strong>
                    <el-tag 
                      v-for="diagnosis in currentRecord.diagnosis.secondary" 
                      :key="diagnosis"
                      type="warning"
                      class="diagnosis-tag"
                    >
                      {{ diagnosis }}
                    </el-tag>
                  </div>
                  <div class="diagnosis-group" v-if="currentRecord.diagnosis.differential.length > 0">
                    <strong>鉴别诊断：</strong>
                    <el-tag 
                      v-for="diagnosis in currentRecord.diagnosis.differential" 
                      :key="diagnosis"
                      type="info"
                      class="diagnosis-tag"
                    >
                      {{ diagnosis }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="治疗方案" name="treatment">
            <div class="treatment-content">
              <div class="treatment-item">
                <h4>药物治疗</h4>
                <el-table :data="currentRecord.treatment.medications" border>
                  <el-table-column prop="name" label="药品名称" />
                  <el-table-column prop="dosage" label="剂量" />
                  <el-table-column prop="frequency" label="频次" />
                  <el-table-column prop="duration" label="疗程" />
                  <el-table-column prop="notes" label="备注" />
                </el-table>
              </div>
              <div class="treatment-item" v-if="currentRecord.treatment.procedures.length > 0">
                <h4>治疗操作</h4>
                <ul>
                  <li v-for="procedure in currentRecord.treatment.procedures" :key="procedure">
                    {{ procedure }}
                  </li>
                </ul>
              </div>
              <div class="treatment-item">
                <h4>医嘱建议</h4>
                <ul>
                  <li v-for="advice in currentRecord.treatment.advice" :key="advice">
                    {{ advice }}
                  </li>
                </ul>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="随访安排" name="followup">
            <div class="followup-content">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="是否需要随访">
                  <el-tag :type="currentRecord.followUp.required ? 'success' : 'info'">
                    {{ currentRecord.followUp.required ? '是' : '否' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="随访日期" v-if="currentRecord.followUp.required">
                  {{ currentRecord.followUp.date }}
                </el-descriptions-item>
                <el-descriptions-item label="随访说明" v-if="currentRecord.followUp.required">
                  {{ currentRecord.followUp.instructions }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>

          <el-tab-pane label="签名记录" name="signature">
            <div class="signature-content">
              <el-table :data="currentRecord.signatures" border>
                <el-table-column prop="role" label="签名角色" />
                <el-table-column prop="doctorName" label="签名医生" />
                <el-table-column prop="signDate" label="签名时间">
                  <template #default="{ row }">
                    {{ formatDateTime(row.signDate) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                  <template #default="{ row }">
                    <el-tag :type="row.status === '已签名' ? 'success' : 'warning'">
                      {{ row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 模板管理对话框 -->
    <el-dialog
      v-model="showTemplateDialog"
      title="病历模板管理"
      width="800px"
    >
      <div class="template-management">
        <el-empty description="模板管理功能开发中" />
      </div>
    </el-dialog>

    <!-- 待签名病历对话框 -->
    <el-dialog
      v-model="showPendingDialog"
      title="待签名病历"
      width="900px"
    >
      <el-table :data="pendingSignatureRecords" max-height="400">
        <el-table-column prop="patientName" label="患者" />
        <el-table-column prop="doctorName" label="医生" />
        <el-table-column prop="department" label="科室" />
        <el-table-column prop="visitDate" label="就诊日期" />
        <el-table-column prop="chiefComplaint" label="主诉" show-overflow-tooltip />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleQuickSign(row)">
              立即签名
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Document, Download, Search, ArrowDown, Calendar, 
  EditPen, Files
} from '@element-plus/icons-vue'
import { useMedicalRecordStore, type MedicalRecord } from '@/stores/modules/medical-record'
import { usePatientStore } from '@/stores/modules/patient'
import { useDoctorStore } from '@/stores/modules/doctor'

const recordStore = useMedicalRecordStore()
const patientStore = usePatientStore()
const doctorStore = useDoctorStore()

// 响应式数据
const searchQuery = ref('')
const filterStatus = ref('')
const filterDepartment = ref('')
const filterVisitType = ref('')
const dateRange = ref<[Date, Date] | null>(null)
const currentPage = ref(1)
const pageSize = ref(20)
const activeTab = ref('basic')

// 对话框状态
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const showTemplateDialog = ref(false)
const showPendingDialog = ref(false)

// 表单数据
const createFormRef = ref()
const createForm = ref({
  patientId: '',
  visitType: '门诊' as MedicalRecord['visitType'],
  visitDate: new Date().toISOString().split('T')[0]
})
const selectedTemplate = ref('')

const createRules = {
  patientId: [
    { required: true, message: '请选择患者', trigger: 'change' }
  ],
  visitType: [
    { required: true, message: '请选择就诊类型', trigger: 'change' }
  ],
  visitDate: [
    { required: true, message: '请选择就诊日期', trigger: 'change' }
  ]
}

const selectedRecords = ref<MedicalRecord[]>([])
const loading = ref(false)

// 计算属性
const filteredRecords = computed(() => {
  let result = recordStore.medicalRecords
  
  if (searchQuery.value) {
    result = recordStore.searchMedicalRecords(searchQuery.value)
  }
  
  if (filterStatus.value) {
    result = result.filter(r => r.status === filterStatus.value)
  }
  
  if (filterDepartment.value) {
    result = result.filter(r => r.department === filterDepartment.value)
  }
  
  if (filterVisitType.value) {
    result = result.filter(r => r.visitType === filterVisitType.value)
  }
  
  if (dateRange.value) {
    const [start, end] = dateRange.value
    const startDate = start.toISOString().split('T')[0]
    const endDate = end.toISOString().split('T')[0]
    result = result.filter(r => r.visitDate >= startDate && r.visitDate <= endDate)
  }
  
  return result
})

const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRecords.value.slice(start, end)
})

const currentRecord = computed(() => recordStore.currentRecord)
const recordStats = computed(() => recordStore.getMedicalRecordStats())
const templates = computed(() => recordStore.getTemplates())
const patients = computed(() => patientStore.patients)

const pendingSignatureRecords = computed(() => {
  return recordStore.getPendingSignatureRecords('D001', '主治医师')
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleDateRangeChange = () => {
  currentPage.value = 1
}

const handleSelectionChange = (selection: MedicalRecord[]) => {
  selectedRecords.value = selection
}

const handleRowClick = (row: MedicalRecord) => {
  recordStore.currentRecord = row
}

const handleViewDetail = (record: MedicalRecord) => {
  recordStore.currentRecord = record
  showDetailDialog.value = true
}

const handleEdit = (record: MedicalRecord) => {
  // 跳转到病历编辑页面
  ElMessage.info('跳转到病历编辑页面')
}

const handleSign = async (record: MedicalRecord) => {
  try {
    await ElMessageBox.confirm(
      `确定要签名病历"${record.patientName}"吗？`,
      '确认签名',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await recordStore.signMedicalRecord(record.id, 'D001', '王医生', '主治医师')
    ElMessage.success('签名成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('签名失败')
    }
  }
}

const handleMoreActions = async (command: string, record: MedicalRecord) => {
  if (command === 'copy') {
    ElMessage.info('复制病历功能开发中')
  } else if (command === 'template') {
    ElMessage.info('保存为模板功能开发中')
  } else if (command === 'print') {
    ElMessage.info('打印病历功能开发中')
  } else if (command === 'export') {
    ElMessage.info('导出PDF功能开发中')
  } else if (command === 'archive') {
    try {
      await recordStore.updateMedicalRecord(record.id, { status: '已归档' })
      ElMessage.success('归档成功')
    } catch (error) {
      ElMessage.error('归档失败')
    }
  } else if (command === 'delete') {
    try {
      await ElMessageBox.confirm(
        `确定要删除病历"${record.patientName}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      await recordStore.deleteMedicalRecord(record.id)
      ElMessage.success('删除成功')
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }
}

const handlePatientSelect = (patientId: string) => {
  // 可以根据患者信息预填一些数据
}

const handleCreateRecord = async () => {
  try {
    await createFormRef.value.validate()
    
    const patient = patients.value.find(p => p.id === createForm.value.patientId)
    if (!patient) {
      ElMessage.error('患者信息不存在')
      return
    }

    const newRecord = {
      patientId: createForm.value.patientId,
      patientName: patient.name,
      doctorId: 'D001', // 当前登录医生
      doctorName: '王医生',
      department: '内分泌科',
      visitDate: createForm.value.visitDate,
      visitType: createForm.value.visitType,
      chiefComplaint: '',
      presentIllness: '',
      pastHistory: '',
      familyHistory: '',
      personalHistory: '',
      physicalExamination: '',
      auxiliaryExamination: [],
      diagnosis: {
        primary: [],
        secondary: [],
        differential: []
      },
      treatment: {
        medications: [],
        procedures: [],
        advice: []
      },
      followUp: {
        required: false,
        date: '',
        instructions: ''
      },
      attachments: [],
      status: '草稿' as const
    }

    await recordStore.createMedicalRecord(newRecord)
    ElMessage.success('病历创建成功')
    showCreateDialog.value = false
    resetCreateForm()
  } catch (error) {
    console.error('创建病历失败:', error)
  }
}

const resetCreateForm = () => {
  createFormRef.value?.resetFields()
  selectedTemplate.value = ''
}

const handleQuickSign = (record: MedicalRecord) => {
  handleSign(record)
  showPendingDialog.value = false
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

const exportRecords = () => {
  ElMessage.info('导出功能开发中')
}

// 辅助方法
const canSign = (record: MedicalRecord) => {
  return record.status === '已完成' && 
         !record.signatures.some(s => s.role === '主治医师' && s.status === '已签名')
}

const getVisitTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    '门诊': 'primary',
    '急诊': 'danger',
    '住院': 'warning',
    '体检': 'success'
  }
  return colorMap[type] || 'info'
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '草稿': 'info',
    '已完成': 'primary',
    '已审核': 'success',
    '已归档': 'warning'
  }
  return colorMap[status] || 'info'
}

const getSignatureColor = (signatures: MedicalRecord['signatures']) => {
  const allSigned = signatures.every(s => s.status === '已签名')
  return allSigned ? 'success' : 'warning'
}

const getSignatureText = (signatures: MedicalRecord['signatures']) => {
  const signedCount = signatures.filter(s => s.status === '已签名').length
  return `${signedCount}/${signatures.length}`
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

onMounted(() => {
  recordStore.getMedicalRecords()
  patientStore.getPatients()
  doctorStore.getDoctors()
})
</script>

<style lang="scss" scoped>
.medical-record-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.stats-cards {
  margin-bottom: 20px;

  .stat-card {
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    &.warning:hover {
      border-color: #E6A23C;
    }

    .stat-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 24px;
      }

      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 700;
          color: #303133;
          line-height: 1;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }
  }
}

.search-card {
  margin-bottom: 20px;
}

.diagnosis-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.more-diagnoses {
  font-size: 12px;
  color: #999;
}

.signature-status {
  .no-signature {
    color: #999;
    font-size: 12px;
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.record-detail {
  .history-content, .examination-content, .treatment-content, .followup-content {
    .history-item, .exam-item, .treatment-item {
      margin-bottom: 20px;

      h4 {
        margin: 0 0 8px 0;
        color: #303133;
        font-weight: 600;
      }

      p {
        margin: 0;
        line-height: 1.6;
        color: #606266;
      }

      ul {
        margin: 0;
        padding-left: 20px;
        color: #606266;
      }
    }

    .diagnosis-section {
      .diagnosis-group {
        margin-bottom: 12px;

        strong {
          display: inline-block;
          margin-right: 8px;
          margin-bottom: 4px;
        }
      }
    }
  }
}

.create-form {
  margin-bottom: 20px;
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .stats-cards {
    :deep(.el-col) {
      margin-bottom: 16px;
    }
  }

  .search-card {
    :deep(.el-row) {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style>